/**
 * jims.
 */
package com.jims.api.v1.controller.register;


import com.jims.master.common.data.Message;
import com.jims.master.common.utils.*;
import com.jims.master.common.web.BaseController;
import com.jims.master.modules.base.user.entity.MasterBaseinfo;
import com.jims.master.modules.base.user.entity.MasterContactinfo;
import com.jims.master.modules.base.user.service.MasterBaseinfoService;

import com.jims.master.modules.sys.entity.OrgDept;
import com.jims.master.modules.sys.entity.SysLoginName;
import com.jims.master.modules.sys.entity.User;
import com.jims.master.modules.sys.service.*;
import com.jims.master.modules.sys.utils.UserUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 注册Controller
 * @author WangYq
 * @version 2017-5-15
 */
@RestController
@RequestMapping(value = "/regist")
public class RegisterController  {
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private MasterBaseinfoService masterBaseinfoService;
	@Autowired
	private SysLoginNameService sysLoginNameService;
	@Autowired
	private UserService userService;
    /**
     * @Title: regValidateEistenceV100
     * @Description: （验证手机号是否已注册）
     * @param mobile
     * @return java.lang.String
     * @author WangYQ
     * @date 2017-11-17
     * @throws
     */
    @RequestMapping(value = "V200/regValidateEistence",method ={RequestMethod.GET,RequestMethod.POST})
    public String validateEistence(@RequestParam(required=true) String mobile,String openid,HttpServletRequest request) {
        Message msg=new Message();
        String userId=getUserId(mobile);
        if(StringUtils.isNotBlank(userId)){
            User user=userService.get(userId);
            user.setOpenid(openid);
            userService.updateOpenid(user);
            msg.setData(user);
        }else{
            msg.setData(null);
        }
        return SecurityUtil.encryptMsgData(msg);
    }
    /**
	 * @Title: regValidateEistenceV100
	 * @Description: （验证手机号是否已注册）
	 * @param mobile
	 * @return java.lang.String
	 * @author WangYQ
	 * @date 2017-11-17
	 * @throws
	 */
	@RequestMapping(value = "V100/regValidateEistence",method ={RequestMethod.GET,RequestMethod.POST})
	public String regValidateEistence(@RequestParam(required=true) String mobile,HttpServletRequest request) {
		Message msg=new Message();
		String userId=getUserId(mobile);
		if(userId==null||userId.equals("")){
			msg.setErrCode("1");
			msg.setData("您输入的手机号码不存在");
		}else{
			msg.setStatus("0");
			msg.setData("您输入的手机号码已存在");
		}
		return SecurityUtil.encryptMsgData(msg);
	}

	/**
	 * @Title: settingPasswordV100
	 * @Description: （普通用户注册）
	 * @param mobile 用户手机号
	 * @param password 密码
	 * @param userType 用户类型
	 * @return java.lang.String
	 * @author WangYQ
	 * @date 2017-11-17
	 * @throws
	 */
	@RequestMapping(value = "V100/settingPassword",method ={RequestMethod.GET,RequestMethod.POST})
	public String settingPassword(@RequestParam(required=true) String mobile, @RequestParam(required=true) String password,  @RequestParam(required=true) String payOpenid,String userType, HttpServletRequest request, HttpServletResponse response) throws IOException {
		Message msg = new Message();
		String userId=getUserId(mobile);
		if(userId!=null&&!userId.equals("")){
			msg.setStatus("414");
			msg.setErrCode("414");
			msg.setErrMsg("您输入的手机号码已存在");
			return SecurityUtil.encryptMsgData(msg);
		}
		User user=new User();
		int i=userRegist(mobile,password, userType,null,payOpenid);
		if(i>0){
			msg.setStatus("200");
			msg.setData("恭喜您，注册成功！");
		}else{
			msg.setErrCode("414");
			msg.setErrMsg("注册失败！！");
		}
		return SecurityUtil.encryptMsgData(msg);
	}

	/**
	 * @Title: doctorRegisterV100
	 * @Description: （医生注册提交信息）
	 * @param mobile
	 * @param password
	 * @param userType
	 * @param name
	 * @param placeAddress 地址
	 * @param workName 单位名称
	 * @param deptCode 科室编号
	 * @param title 职称
	 * @param telephone 固定电话
	 * @return java.lang.String
	 * @author WangYQ
	 * @date 2017-11-19
	 * @throws
	 */
	@RequestMapping(value = "V100/doctorRegister",method ={RequestMethod.GET,RequestMethod.POST})
	public String doctorRegister(@RequestParam(required=true) String mobile,@RequestParam(required=true) String password,@RequestParam(required=true) String userType,@RequestParam(required=true) String name,@RequestParam(required=true) String placeAddress,@RequestParam(required=true) String workName,@RequestParam(required=true) String deptCode,@RequestParam(required=true) String title,String telephone,HttpServletRequest request, HttpServletResponse response) throws IOException {
		SysLoginName sysLoginName=new SysLoginName();
		User user=new User();
//		基本信息
		MasterBaseinfo masterBaseinfo=new MasterBaseinfo();
//		masterBaseinfo.setIdCard(loginName);
		masterBaseinfo.setName(name);
//		默认头像
//		masterBaseinfo.setHeadPath("/static/images/index/beautiful_woman.png");
//		基本信息子表
		MasterContactinfo masterContactinfo=new MasterContactinfo();
		masterContactinfo.setPlaceAddress(placeAddress);
		masterContactinfo.setWorkName(workName);
		masterContactinfo.setTelephone(telephone);
		if(mobile.indexOf("@")>0){
			masterContactinfo.setMobilePhone(null);
			sysLoginName.setType("3");
		}else{
			masterContactinfo.setMobilePhone(mobile);
			sysLoginName.setType("0");
		}
		if(mobile.indexOf("@")>0){
			masterContactinfo.setEmail(mobile);
		}else{
			masterContactinfo.setMobilePhone(mobile);
		}
		masterContactinfo.setBaseinfo(masterBaseinfo);
//		科室
		OrgDept orgDept=new OrgDept();
		orgDept.setDeptCode(deptCode);
		user.setUserType(userType);
		user.setCurrentLogin(mobile);
		user.setPassword(password);
		user.setOrgDept(orgDept);
		user.setTitle(title);
		user.setMasterBaseinfo(masterBaseinfo);
		sysLoginName.setLoginName(mobile);
		sysLoginName.setUser(user);
		sysLoginName.setDelFlag("0");
		Message msg=new Message();
		int i= masterBaseinfoService.userRegister(sysLoginName,masterContactinfo);
		if(i>0){
			msg.setStatus("200");
			msg.setData("恭喜您！注册成功");
		}else{
			msg.setErrCode("414");
			msg.setErrMsg("非常抱歉！注册失败");
		}
		return SecurityUtil.encryptMsgData(msg);
	}


	/**
	 * @Title: wxBindingRegistV100
	 * @Description: （微信绑定注册）
	 * @param openid
	 * @return java.lang.String
	 * @author WangYQ
	 * @date 2017-12-16
	 * @throws
	 */
	@RequestMapping(value = "V100/wxBindingRegist",method ={RequestMethod.GET,RequestMethod.POST})
	public String wxBindingRegist(@RequestParam(required=true)String mobile,String password,@RequestParam(required=true)String openid,String payOpenid,@RequestParam(required=true)String userType,HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.debug("微信注册手机号："+mobile);
//		默认密码
		if(password==null|| password.equals("")){
			password="123456";
		}
		Message msg=new Message();
//		判断手机号是否注册，没注册就让注册
		String userId=getUserId(mobile);
		if(userId ==null|| userId.equals("")){
			int i=userRegist(mobile,password,userType,openid,payOpenid);
			if(i==1){
				User user = new User();
				user.setCurrentLogin(mobile);
				user.setPassword(password);
				user.setUserType(userType);
				msg.setData(user);
			}else{
				msg.setStatus("0");
				msg.setErrCode("414");
				msg.setErrMsg("微信账号绑定与注册失败！");
			}
		}else{
//			再调用注册方法的时候已经调用登录中wxCheckCode方法
			User user=userService.get(userId);
			/*if("3".equals(userType)){
				user.setOpenid(openid);
			}else {
				user.setDocOpenid(openid);
			}*/
			if (userType.equals("3")){
				user.setPayOpenid(payOpenid);
			}
			user.setOpenid(openid);
			int wx=userService.updateOpenid(user);
			if(wx==1){
				User loginUser = new User();
				user.setCurrentLogin(user.getCurrentLogin());
				user.setPassword(user.getPassword());
				user.setUserType(user.getUserType());
				msg.setData(user);
			}else{
				msg.setStatus("0");
				msg.setErrCode("414");
				msg.setErrMsg("openid与user表绑定失败！");
			}
		}
		return SecurityUtil.encryptMsgData(msg);
	}
    /**
     * @Title: wxBindingRegistV100
     * @Description: （微信绑定注册）
     * @param openid
     * @return java.lang.String
     * @author WangYQ
     * @date 2017-12-16
     * @throws
     */
    @RequestMapping(value = "V200/wxBindingRegist",method ={RequestMethod.GET,RequestMethod.POST})
    public String weiXinBindingRegist(@RequestParam(required=true)String mobile,String password,@RequestParam(required=true)String openid,@RequestParam(required=true)String docOpenid,@RequestParam(required=true)String userType,HttpServletRequest request, HttpServletResponse response) throws IOException {
//		默认密码
        if(password==null|| password.equals("")){
            password="123456";
        }
        Message msg=new Message();
//      注册
        int i=userRegist(mobile,password,userType,openid,docOpenid);
        if(i==1){
            User user = new User();
            user.setCurrentLogin(mobile);
            user.setPassword(password);
            user.setUserType(userType);
            msg.setData(user);
        }else{
            msg.setStatus("0");
            msg.setErrCode("414");
            msg.setErrMsg("微信账号绑定与注册失败！");
        }
        return SecurityUtil.encryptMsgData(msg);
    }
	/**
	 * 获取userId
	 * @param  mobile
	 * @return String
	 */
	public String getUserId(String mobile) {
		String userId=sysLoginNameService.findValidate(mobile);
		return userId;
	}
	/**
	 * 普通用户注册
	 * @param  mobile
	 * @param  password
	 * @param  userType
	 * @param  openid
	 * @return String
	 */
	public int userRegist(String mobile, String password, String userType,String openid,String payOpenid) throws IOException {



		User userdata = UserUtils.getUser();

		SysLoginName sysLoginName = new SysLoginName();
//		userType="3";
		if(mobile.indexOf("@")>0){
//			保存登录类型
			sysLoginName.setType("3");
		}else{
//			保存登录类型
			sysLoginName.setType("0");
		}
//		给user对象赋值
		userdata.setUserType(userType);
		userdata.setCurrentLogin(mobile);
		userdata.setPassword(password);
//		如果是个人绑定到openid中，医生绑定到doc_openid中
		/*if("3".equals(userType)){
			user.setOpenid(openid);
		}else{
			user.setDocOpenid(openid);
		}*/
		userdata.setOpenid(openid);
		//判断是医生端还是个人端
		if(userType.equals("2")){
			userdata.setDocOpenid(payOpenid);
		}else {
			userdata.setPayOpenid(payOpenid);
		}
		sysLoginName.setLoginName(mobile);
		sysLoginName.setUser(userdata);
		sysLoginName.setDelFlag("0");
		int i=sysLoginNameService.userRegister(sysLoginName);
		return i;
	}
	/**
	 * @Title: docAddUserV100
	 * @Description: （医生添加患者）
	 * @param mobile 患者电话号码
	 * @param idCard 患者身份证号
	 * @param sex 患者性别
	 * @param age 患者年龄
	 * @param name 患者姓名
	 * @param doctorId 医生id
	 * @return java.lang.String
	 * @author WangYQ
	 * @date 2018-03-16
	 * @throws
	 */
	@RequestMapping(value = "V100/docAddUser",method ={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
    public String docAddUser(@RequestParam(required = true)String mobile,String idCard,@RequestParam(required = true)String sex,@RequestParam(required = true)String age,@RequestParam(required = true)String name,@RequestParam(required = true)String doctorId){
        Message msg=new Message();
        String id = masterBaseinfoService.docAddUser(mobile,idCard,sex,age,name,doctorId);
        if(StringUtils.isNotEmpty(id)){
            MasterBaseinfo masterBaseinfo = masterBaseinfoService.get(id);
            msg.setData(masterBaseinfo);
        }else {
            msg.setStatus("0");
            msg.setData("添加失败");
        }
        return SecurityUtil.encryptMsgData(msg);
    }
}
